<template>
    <el-card class="profile-card">
        <div class="profile-header">
            <div class="avatar-wrap">
                <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload"
                    :on-success="handleAvatarSuccess" :http-request="mockUpload">
                    <img v-if="avatarUrl" :src="avatarUrl" class="avatar" />
                    <div v-else class="avatar placeholder">{{ (userName || 'U').charAt(0).toUpperCase() }}</div>
                </el-upload>
                <div class="user-meta">
                    <div class="user-name">{{ userName || '未登录' }}</div>
                    <div class="user-role">角色：{{ userRole || '未分配角色' }}</div>
                </div>
            </div>
        </div>

        <el-divider />

        <el-tabs v-model="activeTab" type="card">
            <el-tab-pane label="个人资料" name="profile">
                <el-form ref="profileFormRef" :model="profileForm" :rules="profileRules" label-width="120px"
                    class="pwd-form">
                    <el-form-item label="用户账号" prop="userAccount">
                        <el-input v-model.trim="profileForm.userAccount" placeholder="请输入用户账号" />
                    </el-form-item>
                    <el-form-item label="用户姓名" prop="userName">
                        <el-input v-model.trim="profileForm.userName" placeholder="请输入用户姓名" />
                    </el-form-item>
                    <el-form-item label="所属岗位" prop="positionName">
                        <el-input v-model.trim="profileForm.positionName" placeholder="请输入所属岗位" />
                    </el-form-item>
                    <el-form-item label="所在部门" prop="organizationName">
                        <el-input v-model.trim="profileForm.organizationName" placeholder="请输入所在部门" />
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                        <el-radio-group v-model="profileForm.gender">
                            <el-radio :label="1">男</el-radio>
                            <el-radio :label="2">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                        <el-input v-model.trim="profileForm.mobile" placeholder="请输入手机号" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" :loading="savingProfile" @click="onSaveProfile">保存</el-button>
                        <el-button @click="onReloadProfile">重载</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>

            <el-tab-pane label="修改密码" name="password">
                <el-form ref="pwdFormRef" :model="pwdForm" :rules="pwdRules" label-width="120px" class="pwd-form">
                    <el-form-item label="原密码" prop="oldPassword">
                        <el-input v-model.trim="pwdForm.oldPassword" type="password" show-password
                            placeholder="请输入原密码" />
                    </el-form-item>
                    <el-form-item label="新密码" prop="newPassword">
                        <el-input v-model.trim="pwdForm.newPassword" type="password" show-password
                            placeholder="请输入新密码（至少6位）" />
                    </el-form-item>
                    <el-form-item label="确认新密码" prop="confirmPassword">
                        <el-input v-model.trim="pwdForm.confirmPassword" type="password" show-password
                            placeholder="请再次输入新密码" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" :loading="saving" @click="onChangePassword">修改密码</el-button>
                        <el-button @click="onReset">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
        </el-tabs>

        <el-divider />

        <div class="actions">
            <el-button type="danger" @click="onLogout">退出登录</el-button>
        </div>
    </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import myaxios from '@/http/MyAxios'

const router = useRouter()

const userName = ref<string>(localStorage.getItem('username') || '')
const userRole = ref<string>(localStorage.getItem('userRole') || '')

const activeTab = ref('profile')

// 头像
const avatarUrl = ref<string>('')
function beforeAvatarUpload(file: File) {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isImage) ElMessage.error('只能上传图片文件')
    if (!isLt2M) ElMessage.error('图片大小不能超过 2MB')
    return isImage && isLt2M
}

// 个人资料
const profileFormRef = ref<FormInstance>()
const profileForm = reactive({
    userAccount: localStorage.getItem('userAccount') || '',
    userName: localStorage.getItem('username') || '',
    positionName: localStorage.getItem('positionName') || '',
    organizationName: localStorage.getItem('organizationName') || '',
    gender: 1,
    mobile: localStorage.getItem('mobile') || ''
})
const profileRules: FormRules = {
    userAccount: [{ required: true, message: '请输入用户账号', trigger: 'blur' }],
    userName: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
}
const savingProfile = ref(false)
async function loadProfile() {
    try {
        const res = await myaxios({ url: '/api/User/GetMyProfile', method: 'get' })
        const droot: any = res?.data ?? {}
        const d: any = (droot?.data && Object.keys(droot).length <= 3) ? (droot.data || {}) : droot
        if (d) {
            // 账号/姓名
            profileForm.userAccount = d.userAccount ?? d.account ?? d.userCode ?? profileForm.userAccount
            profileForm.userName = d.userName ?? d.realName ?? d.nickname ?? profileForm.userName
            // 岗位/部门
            profileForm.positionName = d.positionName ?? d.position ?? d.jobTitle ?? profileForm.positionName
            profileForm.organizationName = d.organizationName ?? d.departmentName ?? d.orgName ?? profileForm.organizationName
            // 性别（兼容字符串/数字）
            const sex = d.gender ?? d.sex
            if (sex !== undefined && sex !== null) {
                const sexStr = String(sex).toLowerCase()
                if (sexStr === '1' || sexStr === 'male' || sexStr === '男') profileForm.gender = 1
                else if (sexStr === '2' || sexStr === 'female' || sexStr === '女') profileForm.gender = 2
            }
            // 手机（若接口未返回，保留本地）
            profileForm.mobile = d.mobile ?? d.phone ?? d.tel ?? profileForm.mobile
            // 头像
            if (d.avatarUrl || d.avatar || d.headImgUrl) {
                const url = d.avatarUrl ?? d.avatar ?? d.headImgUrl
                avatarUrl.value = String(url)
            }
            // 同步抬头展示名
            userName.value = profileForm.userName
            localStorage.setItem('username', profileForm.userName)
        }
    } catch { }
}
function onReloadProfile() {
    loadProfile()
}
function onSaveProfile() {
    profileFormRef.value?.validate(async (valid) => {
        if (!valid) return
        savingProfile.value = true
        try {
            const res = await myaxios({ url: '/api/User/UpdateMyProfile', method: 'post', data: profileForm })
            if (res?.data?.code === 200) {
                ElMessage.success(res?.data?.message || '保存成功')
                userName.value = profileForm.userName
                localStorage.setItem('username', profileForm.userName)
            } else {
                ElMessage.error(res?.data?.message || '保存失败')
            }
        } catch {
            ElMessage.error('保存失败')
        } finally {
            savingProfile.value = false
        }
    })
}

onMounted(() => {
    loadProfile()
})
// 切换到“个人资料”时自动刷新
watch(activeTab, (v) => {
    if (v === 'profile') loadProfile()
})
// 演示用：不实际上传，仅本地预览
function mockUpload(options: any) {
    const reader = new FileReader()
    reader.onload = () => {
        avatarUrl.value = String(reader.result || '')
        options?.onSuccess?.({}, options.file)
    }
    reader.readAsDataURL(options.file)
}
function handleAvatarSuccess() {
    ElMessage.success('头像已更新（本地预览）')
}

// 修改密码
const pwdFormRef = ref<FormInstance>()
const pwdForm = reactive({ oldPassword: '', newPassword: '', confirmPassword: '' })
const pwdRules: FormRules = {
    oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '至少6位', trigger: 'blur' },
    ],
    confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
            validator: (_, v, cb) => {
                if (v !== pwdForm.newPassword) cb(new Error('两次输入不一致'))
                else cb()
            },
            trigger: 'blur',
        },
    ],
}
const saving = ref(false)
function onChangePassword() {
    pwdFormRef.value?.validate(async (valid) => {
        if (!valid) return
        if (pwdForm.oldPassword === pwdForm.newPassword) {
            ElMessage.warning('新密码不能与原密码相同')
            return
        }
        saving.value = true
        try {
            // 调整为你的后端接口
            const res = await myaxios({
                url: '/api/User/ChangePassword',
                method: 'post',
                data: { oldPassword: pwdForm.oldPassword, newPassword: pwdForm.newPassword },
            })
            if (res.data?.code === 200) {
                ElMessage.success(res.data?.message || '密码修改成功')
                onReset()
            } else {
                ElMessage.error(res.data?.message || '密码修改失败')
            }
        } catch (e) {
            ElMessage.error('密码修改失败')
        } finally {
            saving.value = false
        }
    })
}
function onReset() {
    pwdForm.oldPassword = ''
    pwdForm.newPassword = ''
    pwdForm.confirmPassword = ''
}

// 退出登录
function onLogout() {
    ElMessageBox.confirm('确认退出登录吗？', '提示', { type: 'warning' })
        .then(() => {
            try {
                localStorage.removeItem('token')
                localStorage.removeItem('authToken')
                localStorage.removeItem('userRole')
                localStorage.removeItem('username')
                sessionStorage.removeItem('token')
            } catch { }
            router.replace({ name: 'Login' })
        })
        .catch(() => { })
}
</script>

<style scoped>
.profile-card {
    max-width: 760px;
    margin: 0 auto;
}

.avatar-wrap {
    display: flex;
    align-items: center;
    gap: 16px;
}

.avatar-uploader {
    cursor: pointer;
}

.avatar {
    width: 72px;
    height: 72px;
    border-radius: 50%;
    object-fit: cover;
}

.avatar.placeholder {
    display: grid;
    place-items: center;
    background: #0ea5e9;
    color: #fff;
    font-weight: 700;
}

.el-tabs--card :deep(.el-tabs__header) {
    margin-bottom: 8px;
}

.user-meta .user-name {
    font-weight: 700;
    font-size: 16px;
}

.user-meta .user-role {
    color: #64748b;
    font-size: 13px;
    margin-top: 2px;
}

.pwd-form {
    max-width: 520px;
    margin-top: 12px;
}

.actions {
    margin-top: 12px;
}
</style>
